package controller

import (
	"github.com/gin-gonic/gin"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_workflow/model"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/internal/module/job_workflow/service"
	"openeuler.org/PilotGo/PilotGo-plugin-automation/pkg/response"
)

func CreateWorkflow(c *gin.Context) {
	var workflow model.TaskWorkflowDTO
	if err := c.ShouldBindJSON(&workflow); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	if err := service.CreateWorkflow(&workflow); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}

func DeleteWorkflow(c *gin.Context) {
	var ids struct {
		ID []int `json:"id"`
	}
	if err := c.ShouldBindJSON(&ids); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	if err := service.DeleteWorkflow(ids.ID); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}

func UpdateWorkflow(c *gin.Context) {
	var workflow model.TaskWorkflowDTO
	if err := c.ShouldBindJSON(&workflow); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	if err := service.UpdateWorkflow(&workflow); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}

func QueryWorkflow(c *gin.Context) {
	query := &response.PagedQuery{}
	if err := c.ShouldBindQuery(query); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	paged := c.Query("paged")
	publishStatus := c.Query("publish_status")
	tag := c.Query("tag")
	if paged == "true" {
		workflows, total, err := service.QueryWorkflow(query, publishStatus, tag)
		if err != nil {
			response.Fail(c, nil, err.Error())
			return
		}
		response.DataPaged(c, workflows, total, query)
		return
	}
	workflows, err := service.GetWorkflows()
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, workflows, "success")
}

func GetWorkflowById(c *gin.Context) {
	workflowId := c.Query("id")
	info, err := service.GetWorkflowById(workflowId)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, info, "success")
}

func PublishWorkflow(c *gin.Context) {
	var id struct {
		ID        int    `json:"id"`
		NewStatus string `json:"new_status"`
	}
	if err := c.ShouldBindJSON(&id); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	if err := service.PublishWorkflow(id.ID, id.NewStatus); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}

func RelatedTaskWorkflowToSync(c *gin.Context) {
	workFolwId := c.Query("id")

	if err := service.RelatedTaskWorkflowToSync(workFolwId); err != nil {
		response.Fail(c, nil, err.Error())
		return
	}
	response.Success(c, nil, "success")
}
